# coding=utf-8
import json
import urllib2
import xmltodict
from flask import Flask, request
from utils.notoken.cReplyMsg import ReplyMsgDemo
from utils.token.cAccessToken import AccessTokenDemo

app = Flask(__name__)
menu_type_list = ['click', 'view', 'scancode_push', 'scancode_waitmsg', 'pic_sysphoto', 'pic_photo_or_album',
                  'pic_weixin', 'location_select', 'media_id', 'view_limited']


@app.route('/token/', methods=['GET', 'POST'])
def wechat_validate():
    rmd = ReplyMsgDemo()
    if request.method == 'GET':
        return rmd.check_status(request)
    elif request.method == 'POST':
        _url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token={}'.format(AccessTokenDemo.get_access_token())
        _req_body = {
            "button": [
                {
                    "type": "click",
                    "name": "点击",
                    "key": "click"
                },
                {
                    "name": "子菜单1",
                    "sub_button": [
                        {
                            "type": "view",
                            "name": "视图",
                            "url": "http://www.baidu.com/"
                        },
                        {
                            "type": "scancode_push",
                            "name": "扫码推送",
                            "key": "scancode_push",
                            "sub_button": []
                        },
                        {
                            "type": "scancode_waitmsg",
                            "name": "扫码带提示",
                            "key": "scancode_waitmsg",
                            "sub_button": []
                        },
                        {
                            "type": "location_select",
                            "name": "发送位置",
                            "key": "location_select"
                        },
                        # {
                        #     "type": "media_id",
                        #     "name": "图片",
                        #     "media_id": "media_id"
                        # },
                    ]
                },
                {
                    "name": "子菜单2",
                    "sub_button": [
                        {
                            "type": "pic_sysphoto",
                            "name": "系统拍照发图",
                            "key": "pic_sysphoto",
                            "sub_button": []
                        },
                        {
                            "type": "pic_photo_or_album",
                            "name": "拍照或者相册发图",
                            "key": "pic_photo_or_album",
                            "sub_button": []
                        },
                        {
                            "type": "pic_weixin",
                            "name": "微信相册发图",
                            "key": "pic_weixin",
                            "sub_button": []
                        },
                        # {
                        #     "type": "view_limited",
                        #     "name": "图文消息",
                        #     "media_id": "view_limited"
                        # },
                    ]
                }
            ]
        }
        _data = json.dumps(_req_body, ensure_ascii=False)
        _req = urllib2.Request(_url, _data)
        _resp = urllib2.urlopen(_req).read()
        _resp_data = json.loads(_resp)
        print _resp_data

        xml = request.data
        req = xmltodict.parse(xml)['xml']
        if req.get('Content') != 'test':
            req['r_code'] = 200
            return rmd.reply_msg(request=req)
        else:
            req['r_code'] = 333
            req['Content'] = 'success'
            return rmd.reply_msg(request=req)


@app.route('/server_ip/get/')
def get_server_ip():
    if request.method == 'GET':
        _url = 'https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token={}'.format(AccessTokenDemo.get_access_token())
        req = urllib2.Request(_url)
        resp = urllib2.urlopen(req).read()
        resp_data = json.loads(resp)
        print resp_data
        server_ip_list = resp_data.get('ip_list')
        return '\t'.join(server_ip_list), 200


@app.route('/kf_service/add/')
def add_kfacount():
    req = request.args
    kf_account = req.get('kf_account')
    nickname = req.get('nickname')
    password = req.get('password')
    _url = 'https://api.weixin.qq.com/customservice/kfaccount/add?access_token={}'.format(
        AccessTokenDemo.get_access_token())
    _data = {
        "kf_account": kf_account,
        "nickname": nickname,
        "password": password
    }
    _data = json.dumps(_data)
    req = urllib2.Request(_url)
    resp = urllib2.urlopen(req, _data).read()
    resp_data = json.loads(resp)
    print resp_data
    return resp


@app.route('/kf_service/update/')
def update_kfacount():
    req = request.args
    kf_account = req.get('kf_account')
    nickname = req.get('nickname')
    password = req.get('password')
    _url = 'https://api.weixin.qq.com/customservice/kfaccount/update?access_token={}'.format(
        AccessTokenDemo.get_access_token())
    _data = {
        "kf_account": kf_account,
        "nickname": nickname,
        "password": password
    }
    _data = json.dumps(_data)
    req = urllib2.Request(_url)
    resp = urllib2.urlopen(req, _data).read()
    resp_data = json.loads(resp)
    print resp_data
    return resp


@app.route('/kf_service/del/')
def del_kfacount():
    req = request.args
    kf_account = req.get('kf_account')
    nickname = req.get('nickname')
    password = req.get('password')
    _url = 'https://api.weixin.qq.com/customservice/kfaccount/del?access_token={}'.format(
        AccessTokenDemo.get_access_token())
    _data = {
        "kf_account": kf_account,
        "nickname": nickname,
        "password": password
    }
    _data = json.dumps(_data)
    req = urllib2.Request(_url)
    resp = urllib2.urlopen(req, _data).read()
    resp_data = json.loads(resp)
    print resp_data
    return resp


@app.route('/kf_service/getkflist/')
def get_kflist():
    _url = 'https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token={}'.format(
        AccessTokenDemo.get_access_token())
    req = urllib2.Request(_url)
    resp = urllib2.urlopen(req).read()
    resp_data = json.loads(resp)
    print resp_data
    return resp


@app.route('/kf_service/uploadheading/')
def uploadheading_kfacount():
    # TODO 传递头像图片
    req = request.args
    kf_account = req.get('kf_account')
    media = req.get('media')
    _url = 'https://api.weixin.qq.com/customservice/kfaccount/uploadheadimg?access_token={0}&kf_account={1}'.format(
        AccessTokenDemo.get_access_token(), kf_account)
    _data = {
        'media': 'img/{}'.format(media)
    }
    _data = json.dumps(_data)
    req = urllib2.Request(_url)
    resp = urllib2.urlopen(req, _data).read()
    resp_data = json.loads(resp)
    print resp_data
    return resp


@app.route('/kf_service/sendmessage/')
def sendmessage_kfacount():
    req = request.args
    touser = req.get('touser')
    content = req.get('content')
    _url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={}'.format(
        AccessTokenDemo.get_access_token())
    _data = {
        "touser": touser,
        "msgtype": "text",
        "text": {
            "content": content
        }
    }
    _data = json.dumps(_data)
    req = urllib2.Request(_url)
    resp = urllib2.urlopen(req, data=_data).read()
    resp_data = json.loads(resp)
    print resp_data
    return resp


@app.route('/kf_service/typing/')
def typing_kfacount(kf_account):
    req = request.args
    touser = req.get('touser')
    _url = 'https://api.weixin.qq.com/cgi-bin/message/custom/typing?access_token={}'.format(
        AccessTokenDemo.get_access_token())
    _data = {
        "touser": touser,
        "command": "Typing"
    }
    _data = json.dumps(_data)
    req = urllib2.Request(_url)
    resp = urllib2.urlopen(req, data=_data).read()
    resp_data = json.loads(resp)
    print resp_data
    return resp


@app.route("/scene_id=<sid>/")
def get_ticket(sid):
    access_token = AccessTokenDemo.get_access_token()
    url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s' % access_token
    req_body = {
        'expire_seconds': 7200,
        'action_name': 'QR_SCENE',
        'action_info': {'scene': {'scene_id': sid}}
    }
    data = json.dumps(req_body)
    req = urllib2.Request(url, data)
    resp = urllib2.urlopen(req).read()
    print resp
    if 'errcode' in resp:
        return 'error'
    else:
        resp_data = json.loads(resp)
        ticket = resp_data['ticket']
        return '<img src="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s">' % ticket


def _test_accesstoken():
    """
    _test_accesstoken()
    >
    648e4cc1.ngrok.io
    """
    app.run(debug=True, host='0.0.0.0', port=8000)


if __name__ == '__main__':
    _test_accesstoken()
